#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDir>
#include <QTime>
#include <QFileDialog>
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);


    this->initUI();
    this->initAudio();

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::initUI()
{
    //通道
    ui->comboBox_channels->addItem("1");
    ui->comboBox_channels->addItem("2");
    ui->comboBox_channels->addItem("4");

    //质量
    ui->horizontalSlider->setRange(0,QMultimedia::VeryHighQuality);
    ui->horizontalSlider->setValue(QMultimedia::NormalQuality);

    //比特率
    ui->comboBox_bitrates->addItem("32000");
    ui->comboBox_bitrates->addItem("64000");
    ui->comboBox_bitrates->addItem("96000");
    ui->comboBox_bitrates->addItem("128000");



}

void MainWindow::initAudio()
{
    //初始化
    probe=new QAudioProbe(this);
    recoder=new QAudioRecorder(this);

    probe->setSource(recoder);

    //状态检测
    connect(recoder,&QAudioRecorder::stateChanged,this,&MainWindow::on_stateChanged);

    //录音时间检测
    connect(recoder,&QAudioRecorder::durationChanged,this,&MainWindow::on_durationChanged);

    //探测器状态
    connect(probe,&QAudioProbe::audioBufferProbed,this,&MainWindow::on_audioBufferProbed);


    //获取所有录制设备并添加到选项中
    QStringList devices=recoder->audioInputs();
    for(const auto& device:devices){
        ui->comboBox_device->addItem(device);
    }

    //支持的编码
    for(auto codec:recoder->supportedVideoCodecs() ){
        ui->comboBox_codec->addItem(codec);
    }

    //支持的采样率
    for(auto rate:recoder->supportedFrameRates()){
        ui->comboBox_sampleRate->addItem(QString::number(rate));
    }

}

void MainWindow::openSaveFile()
{
    //设置保存的文件
    QString path=QDir::homePath();
    QString title="要保存的录音文件";
    QString filter="wav(*.wav)";
    QString selectFile=QFileDialog::getSaveFileName(this,title,path,filter);

    if(!selectFile.isEmpty()){
        this->ui->lineEdit_outputFile->setText(selectFile);
    }
}

void MainWindow::on_stateChanged(QMediaRecorder::State state)
{
    bool isRecode = (state==QMediaRecorder::State::RecordingState);
    ui->actionRecord->setEnabled(!isRecode);
    ui->actionPause->setEnabled(isRecode);
    ui->actionStop->setEnabled(isRecode);
    ui->pushButton_file->setEnabled(isRecode);
}

void MainWindow::on_durationChanged(qint64 duration)
{
    QTime time(0,0,0);
    time=time.addSecs(duration/1000);
    QString timeString=time.toString("hh:mm:ss");
    this->ui->label_passTime->setText(timeString);
}

void MainWindow::on_audioBufferProbed(const QAudioBuffer &buffer)
{
    //处理探测器数据
    ui->spinBox_byteCount->setValue(buffer.byteCount());
    ui->spinBox_duration->setValue(buffer.duration());
    ui->spinBox_frameCount->setValue(buffer.frameCount());
    ui->spinBox_simpleCount->setValue(buffer.sampleCount());

    QAudioFormat format=buffer.format();

    //通道数
    QString str=QString("%1").arg(format.channelCount());
    ui->label_channelsCount->setText(str);

    //字节序
    str= QString::number(format.byteOrder());
    ui->label_byteOrder->setText(str);

     //编码格式
    ui->label_codec->setText(format.codec());


     //采样类型
    str= QString::number(format.sampleType());
    ui->label_simpleType->setText(str);


    //采样大小
    str= QString::number(format.sampleSize());
    ui->label_simpleSize->setText(str);

    //采样率
    str= QString::number(format.sampleRate());
    ui->label_simpleRate->setText(str);

    //每帧字节数
    str= QString::number(format.bytesPerFrame());
    ui->label_frameCount->setText(str);

    str.toStdString();
}

void MainWindow::on_actionRecord_triggered()
{
    if(recoder->state()==QMediaRecorder::State::PausedState){
        recoder->record();
        return;
    }
    //开始录音
    //录制状态就跳过该步骤
    if(recoder->state()!=QMediaRecorder::State::StoppedState){
        return;
    }

    QString selectFile=ui->lineEdit_outputFile->text();
    // 如果路径为空,就打开路径
    if(selectFile.isEmpty()){
        openSaveFile();
        if(selectFile.isEmpty()){
            return;
        }
    }

    if(QFile::exists(selectFile)){
        if(QFile::remove(selectFile)){
            QMessageBox::critical(this,"错误","文件被占用");
            return;
        }
    }

    recoder->setOutputLocation(QUrl::fromLocalFile(selectFile));
    recoder->setAudioInput(ui->comboBox_device->currentText());

    //音频编码设置
    QAudioEncoderSettings settings;
    // 设置编码
    settings.setCodec(ui->comboBox_codec->currentText());
    // 设置比特率
    settings.setSampleRate(ui->comboBox_sampleRate->currentText().toUInt());
    // 通道数
    settings.setChannelCount(ui->comboBox_channels->currentText().toInt());
    // 质量
    settings.setQuality((QMultimedia::EncodingQuality)ui->horizontalSlider->value());
    // 编码模式
    if(this->ui->radioButton->isChecked()){
        settings.setEncodingMode(QMultimedia::EncodingMode::ConstantQualityEncoding);
    }
    else{
        settings.setEncodingMode(QMultimedia::EncodingMode::ConstantBitRateEncoding);
    }
    this->recoder->setAudioSettings(settings);

    //开始录音
    this->recoder->record();
}



void MainWindow::on_pushButton_file_clicked()
{

    this->openSaveFile();
}

void MainWindow::on_actionStop_triggered()
{
    recoder->stop();
}

void MainWindow::on_actionPause_triggered()
{
    recoder->pause();
}

void MainWindow::on_actionExit_triggered()
{
    this->close();
}
